package com.ergwang.dao;

import com.ergwang.Model.User;
import com.ergwang.utils.DruidUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * @author：ergwang
 * @Date: 2020/5/30
 * @Time: 10:29
 */
public class UserDaoImpl implements UserDao {

    public List<User> allUser() {
        QueryRunner runner = new QueryRunner(DruidUtils.getDataSource());
        List<User> query = null;
        try {
            query = runner.query("select * from user", new BeanListHandler<User>(User.class));
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return query;
    }

    /**
     * 根据传入的关键字模糊查询
     * @param word
     * @return
     */
    public List<User> searchUser(String word) {
        QueryRunner runner = new QueryRunner(DruidUtils.getDataSource());
        List<User> query = null;
        try {
            query = runner.query("select * from user where nickname like ?",
                    new BeanListHandler<User>(User.class),
                    "%" + word + "%");
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return query;
    }

    public int deleteUser(String id) {
        QueryRunner runner = new QueryRunner(DruidUtils.getDataSource());
        int update = 0;
        try {
            update = runner.update("delete from user where id = ?", id);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return update;
    }

    public User login(User user) {
        QueryRunner runner = new QueryRunner(DruidUtils.getDataSource());
        try {
            user = runner.query("select * from user where email = ? and pwd = ?",
                    new BeanHandler<User>(User.class),
                    user.getEmail(), user.getPwd());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return user;
    }

    public void signup(User user) {
        QueryRunner runner = new QueryRunner(DruidUtils.getDataSource());
        try {
            runner.update("insert into user values (null,?,?,?,?,?,?)",
                    user.getEmail(),user.getNickname(),user.getPwd(),user.getRecipient(),user.getAddress(),user.getPhone());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
